package com.liukai.novel_info.presenter.impl;


import com.liukai.novel_base.base.BasePresenter;
import com.liukai.novel_commons.API;
import com.liukai.novel_commons.Result;
import com.liukai.novel_commons.utils.LogUtils;
import com.liukai.novel_commons.utils.RetrofitManager;
import com.liukai.novel_info.call_back.INovelCallBack;
import com.liukai.novel_info.presenter.INovelPresenter;

import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class NovelPresenterImpl extends BasePresenter<INovelCallBack> implements INovelPresenter {

    @Override
    public void findNovelById(String novelId) {
        Retrofit retrofit = RetrofitManager.getNovelInstance().getRetrofit();
        API api = retrofit.create(API.class);
        Call<Result> task = api.findNovelInfoById(novelId);
        task.enqueue(new Callback<Result>() {
            @Override
            public void onResponse(Call<Result> call, Response<Result> response) {
                LogUtils.e(getClass(), "=========>" + response.toString());
                if (response.code() == HttpURLConnection.HTTP_OK) {
                    mCallBack.findNovelByIdResult(response.body());
                }
            }

            @Override
            public void onFailure(Call<Result> call, Throwable t) {

            }
        });

    }

    /**
     * 根据小说id和章节id获取小说章节信息
     *
     * @param novelId
     * @param chapterId
     */
    @Override
    public void findNovelChapterById(String novelId, Integer chapterId) {

        Map<String, Object> map = new HashMap<>();
        map.put("novelId", novelId);
        map.put("chapterId", chapterId);
        if (chapterId == 0)
            chapterId += 1;

        Retrofit retrofit = RetrofitManager.getNovelInstance().getRetrofit();
        API api = retrofit.create(API.class);
        Call<Result> novelChapterById = api.findNovelChapterById(chapterId, novelId);
        novelChapterById.enqueue(new Callback<Result>() {
            @Override
            public void onResponse(Call<Result> call, Response<Result> response) {

                LogUtils.e(getClass(), response.toString());
                int code = response.code();
                Result body = response.body();
//                LogUtils.e(getClass(),"code:" + code + ",body:" + body.toString());

                if (code == HttpURLConnection.HTTP_OK) {
                    mCallBack.findNovelChapterByIdResult(body);
                }

            }

            @Override
            public void onFailure(Call<Result> call, Throwable t) {

            }
        });

    }


}
